import { Mesh, Line, Texture, LineBasicMaterial, LineDashedMaterial } from 'three'

export const disposeObject = (object) => {
  if (!object) return

  // 递归处理子对象，确保所有 Mesh 和 Line 都释放
  while (object.children.length > 0) {
    disposeObject(object.children[0])
    object.remove(object.children[0])
  }

  // 处理 Mesh 或 Line 类型对象
  if (object instanceof Mesh || object instanceof Line) {
    // 释放几何体
    if (object.geometry) {
      object.geometry.dispose()
    }

    // 释放材质
    if (object.material) {
      if (Array.isArray(object.material)) {
        object.material.forEach((mat) => disposeMaterial(mat))
      } else {
        disposeMaterial(object.material)
      }
    }
  }

  // 从父级移除
  if (object.parent) {
    object.parent.remove(object)
  }
}

// 释放材质及其贴图
const disposeMaterial = (material) => {
  if (!material) return

  // 释放所有纹理资源
  for (const key in material) {
    if (material[key] && material[key] instanceof Texture) {
      material[key].dispose()
    }
  }

  // 释放材质（包括普通材质和线条材质）
  if (material instanceof LineBasicMaterial || material instanceof LineDashedMaterial) {
    material.dispose()
  } else if (material.dispose) {
    material.dispose()
  }
}
